package org.catdroid.bomba.server.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.catdroid.bomba.server.Constants;

public class DatabaseUtil {

	public static Connection getConnection() {
		
		try {
	        InitialContext ctx = new InitialContext();
			DataSource ds = (DataSource)ctx.lookup(Constants.DB_CONTEXT);
			return ds.getConnection();
			
		} catch (Exception e) {
			System.out.println("Error opening a Connection");
			Connection con = getSimpleConnection();
			if(con!=null){
				return con;
			}
			throw new RuntimeException(e);
		}
	}
	
	public static void CloseResource (Connection connection) {
		if (connection!=null) {
			try {
				connection.close();
			}catch (Exception ex){ }
		}
	}
	public static void CloseResource (PreparedStatement prepared) {
		if (prepared!=null) {
			try {
				prepared.close();
			}catch (Exception ex){ }
		}
	}
	
	 /** Uses DriverManager.  */
	public static Connection getSimpleConnection() {
	    //See your driver documentation for the proper format of this string :
	    String DB_CONN_STRING = "jdbc:mysql://"+Constants.host+":3306/"+Constants.db_name+"?user="+Constants.user+"&password="+Constants.pass;
	    //Provided by your driver documentation. In this case, a MySql driver is used : 
	    String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
//	    String USER_NAME = Constants.user;
//	    String PASSWORD = Constants.pass;
	    
	    Connection result = null;
	    try {
	       Class.forName(DRIVER_CLASS_NAME).newInstance();
	    }
	    catch (Exception ex){
	       log("Check classpath. Cannot load db driver: " + DRIVER_CLASS_NAME);
	    }

	    try {
	      result = DriverManager.getConnection(DB_CONN_STRING);
	    }
	    catch (SQLException e){
	       log( "Driver loaded, but cannot connect to db: " + DB_CONN_STRING);
	    }
	    return result;
	  }

	  private static void log(Object aObject){
	    System.out.println(aObject);
	  }
	
}
